/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.gradleshell.shell.cmds;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.gradleshell.shell.gradle.ICommandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.stereotype.Component;

/**
 *
 * @author jxcommerce<g2commerce@gmail.com>
 */
@Component
public class RunAppCmd implements CommandMarker {

    boolean running = false;
    GradleAppRunner runner;
    @Autowired
    ICommandService commandService;

    @CliAvailabilityIndicator({"run-app"})
    public boolean isCommandAvailable() {
        return true;
    }

    @CliCommand(value = "run-app", help = "run gradle application")
    public String runApp(
            @CliOption(key = "debug", mandatory = false, unspecifiedDefaultValue = "false") boolean debug,
            @CliOption(key = "suspend", mandatory = false, unspecifiedDefaultValue = "false") boolean suspend,
            @CliOption(key = "dbgport", mandatory = false) Integer dbgport,
            @CliOption(key = "slpath", mandatory = false) String slpath
    ) {
        List<String> argList = new ArrayList();
        String msg = processDebugArgs(argList, debug, suspend, dbgport);
        if (!StringUtils.isEmpty(msg)) {
            return msg;
        }
        msg = processSpringLoadedArgs(argList, slpath);
        if (!StringUtils.isEmpty(msg)) {
            return msg;
        }
        String[] argArray = new String[argList.size()];

        msg = doRunApp(argList.toArray(argArray));

        return msg;

    }

    protected String processSpringLoadedArgs(List<String> argList, String slpath) {
        String retMsg = null;
        if (!StringUtils.isEmpty(slpath)) {
            if (fileExists(slpath)) {
                argList.add("-DSLPath=" + slpath);
            } else {
                retMsg = "file not found: " + slpath;
            }
        } else {
            String home = System.getenv("GRADLE_SHELL_HOME");
            if (!StringUtils.isEmpty(home)) {
                String libdir = home + "/lib";
                File fdir = new File(libdir);
                if (fdir.exists() && fdir.isDirectory()) {
                    File[] files = fdir.listFiles(new FilenameFilter() {
                        @Override
                        public boolean accept(File f, String name) {
                            return FilenameUtils.isExtension(name, "jar")
                                    && name.indexOf("springloaded") != -1;
                        }
                    });
                    if (files != null && files.length > 0) {
                        argList.add("-DSLPath=" + files[0].getAbsolutePath());
                    } else {
                        retMsg = "no spring-loaded file found under: " + libdir;
                    }

                } else {
                    retMsg = "no spring-loaded file found under: " + home;
                }
            } else {
                retMsg = "no spring-loaded file found,neither GRADLE_SHELL_HOME environment variable nor slpath property defined";
            }
        }
        return retMsg;
    }

    protected String processDebugArgs(List<String> argList, boolean debug, boolean suspend, Integer dbgport) {
        if (debug) {
            argList.add("-Ddebug=true");
            if (suspend) {
                argList.add("-Dsuspend=true");
            }
            if (dbgport != null) {
                argList.add("-Ddbgport=" + dbgport);
            }
        }
        return null;
    }

//    @CliCommand(value = "stop-app", help = "stop gradle application")
//    public String stopApp() {
//        if (!running) {
//            return "application not running";
//        } else {
//            doStopApp();
//            return "application stoped";
//        }
//    }
    private void doStopApp() {
        if (runner != null) {
            runner.stop();
            runner = null;
        }
    }

    private boolean fileExists(String slpath) {
        File file = new File(slpath);
        return file.exists();
    }

    private String doRunApp(String[] jvmArgs) {
        if (running) {
            return "application already running";
        } else {
            runner = new GradleAppRunner(commandService, jvmArgs);
            runner.start();
            running = true;
            return "application running..";
        }
    }
}
